﻿using System;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using System.Windows;

namespace Game.Level
{
    public class LevelEventArgs : EventArgs
    {
        public GameLevel GameLevel { get; set; }
    }

    [CollectionDataContract(Namespace = "game", ItemName = "Level")]
    public class GameLevels : Collection<GameLevel>
    {
        public static readonly DependencyProperty IndexProperty = DependencyProperty.RegisterAttached(
            "Index", typeof(Int32), typeof(GameLevelDependencyObject), new PropertyMetadata(0, null));

        public static int GetIndex(GameLevel element)
        {
            return (int)element.DependencyObject.GetValue(IndexProperty);
        }

        public static void SetIndex(GameLevel element, int value)
        {
            element.DependencyObject.SetValue(IndexProperty, value);
        }

        public static GameLevels Create()
        {
            return new GameLevels();
        }

        readonly GameLevelEvents _Events = new GameLevelEvents();

        public GameLevelEvents Events
        {
            get { return _Events; }
        }

        [OnDeserialized]
        public void OnDeserialized2(StreamingContext c)
        {
            UpdateIndex();
        }

        protected override void InsertItem(int index, GameLevel item)
        {
            base.InsertItem(index, item);
            UpdateIndex();
            _Events.FireLevelAdded(item);
        }

        protected override void RemoveItem(int index)
        {
            var level = this[index];
            base.RemoveItem(index);
            UpdateIndex();
            _Events.FireLevelRemoved(level);
        }

        void UpdateIndex()
        {
            int index = 0;
            foreach (var level in this)
            {
                SetIndex(level, index);
                _Events.FireLevelUpdated(level);

                index++;
            }
        }

    }
}
